﻿using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using ConverterSystems.UaBrowser.ViewModels;

namespace ConverterSystems.UaBrowser
{
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [CLSCompliant(false)]
    [ComVisible(true)]
    [Guid(GuidList.guidOptionsDialogPersistanceString)]
    public class OptionsDialogPage : UIElementDialogPage
    {
        OptionsDialogPageControl _view;
        UaBrowserViewModel _viewmodel;

        public OptionsDialogPage()
        {
        }

        protected override UIElement Child
        {
            get
            {
                if (_view == null)
                {
                    _view = new OptionsDialogPageControl();
                    var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
                    _viewmodel = componentModel.DefaultExportProvider.GetExportedValue<UaBrowserViewModel>();
                    _view.DataContext = _viewmodel;
                }
                return _view;
            }
        }

        protected override void OnApply(DialogPage.PageApplyEventArgs e)
        {
            if (e.ApplyBehavior == ApplyKind.Apply)
            {
                _view.LayoutRoot.BindingGroup.CommitEdit();
                _viewmodel.SaveSettingsCommand.Execute(null);
            }
            base.OnApply(e);
        }

        protected override void OnClosed(EventArgs e)
        {
            _view.LayoutRoot.BindingGroup.CancelEdit();
            base.OnClosed(e);
        }
    }
}
